package org.me.Anime.Utli;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.LinkedList;
import java.util.Queue;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Bitmap.Config;

public class Algorithm {
	
	public static void FloodFill(Bitmap bmp, Point pt, int targetColor, int replacementColor) 
	{
	    Queue<Point> q = new LinkedList<Point>();
	    q.add(pt);
	    while (q.size() > 0) {
	        Point n = q.poll();
	        if (bmp.getPixel(n.x, n.y) != targetColor )
	            continue;
	        
	        Point w = n, e = new Point(n.x + 1, n.y);
	        while ((w.x > 0) && (bmp.getPixel(w.x, w.y) == targetColor ||bmp.getPixel(w.x, w.y) == Color.BLUE)) {
	        	
	            bmp.setPixel(w.x, w.y, replacementColor);
	            
	            if ((w.y > 0) && (bmp.getPixel(w.x, w.y - 1) == targetColor))
	                q.add(new Point(w.x, w.y - 1));
	            if ((w.y < bmp.getHeight() - 1)
	                    && (bmp.getPixel(w.x, w.y + 1) == targetColor))
	                q.add(new Point(w.x, w.y + 1));
	            w.x--;
	        }
	        while ((e.x < bmp.getWidth() - 1)
	                && (bmp.getPixel(e.x, e.y) == targetColor)) {
	            bmp.setPixel(e.x, e.y, replacementColor);

	            if ((e.y > 0) && (bmp.getPixel(e.x, e.y - 1) == targetColor))
	                q.add(new Point(e.x, e.y - 1));
	            if ((e.y < bmp.getHeight() - 1)
	                    && (bmp.getPixel(e.x, e.y + 1) == targetColor))
	                q.add(new Point(e.x, e.y + 1));
	            e.x++;
	        }
	    }
	}
	
	 public static Bitmap convertToMutable(Bitmap bitmap) {
			try {
				File file = new File("/mnt/sdcard/sample/temp.txt");
				file.getParentFile().mkdirs();
				RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
				
				int width = bitmap.getWidth();
				int height = bitmap.getHeight();
				
				FileChannel channel = randomAccessFile.getChannel();
				MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width*height*4);
				bitmap.copyPixelsToBuffer(map);
				bitmap.recycle();
				
				bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
				map.position(0);
				bitmap.copyPixelsFromBuffer(map);

				channel.close();
				randomAccessFile.close();
				
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			}
			return bitmap;
		}

}
